import { createContext, useContext } from 'react';

import type { IAction, IState } from './interface';

export * as Types from './constants';

type Dispatch<A> = (value: A) => void;

const CanvasContext = createContext<[IState, Dispatch<IAction>] | undefined>(undefined);

export default CanvasContext;

const Provider = CanvasContext.Provider;

export const useContextSelector = <Selected>(selector: (state: IState) => Selected): Selected => {
  const [state] = useContext(CanvasContext)!;
  const selectedState = selector(state);
  return selectedState as typeof selectedState;
};

export const useContextDispatch = () => {
  const [, dispatch] = useContext(CanvasContext) as [IState, Dispatch<IAction>];
  return dispatch;
};

export { Provider };
